import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, logUserOut } from '@/api/user'

const user = {
  namespaced: true,
  state: {
    username: '',
    token:getToken(),
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.username = userInfo.username
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },
  actions: {
    async GetUserInfo({ commit }) {
      const { data } = await getUserInfo()
      // commit('SET_USERINFO', {username: 'a'})
      commit('SET_USERINFO', data)
    },
    // 用户名登录
    Login({ commit }, token) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      })
    },
    async FedLogOut({ commit }) {
      return new Promise((resolve) => {
        let logoutToken = getToken();
        logUserOut(logoutToken).then(() => {
          commit('SET_TOKEN', '')
          removeToken(getToken())
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    }
  }
}

export default user
